#include "toydialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QSqlError>
#include <QDebug>

ToyDialog::ToyDialog(QWidget *parent)
    : QDialog(parent), m_isEditMode(false)
{
    setWindowTitle("玩具信息");
    setFixedSize(500, 400);
    setupUI();
    loadProcesses();
    
    // 连接验证信号
    connect(m_nameEdit, &QLineEdit::textChanged, this, &ToyDialog::validateInput);
    connect(m_toyIdEdit, &QLineEdit::textChanged, this, &ToyDialog::validateInput);
    connect(m_processListWidget, &QListWidget::itemChanged, this, &ToyDialog::onProcessSelectionChanged);
}

void ToyDialog::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    
    // 玩具编号
    m_toyIdEdit = new QLineEdit();
    m_toyIdEdit->setPlaceholderText("请输入玩具编号");
    formLayout->addRow("玩具编号:", m_toyIdEdit);
    
    // 玩具名称
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText("请输入玩具名称");
    formLayout->addRow("玩具名称:", m_nameEdit);
    
    // 描述
    m_descriptionEdit = new QLineEdit();
    m_descriptionEdit->setPlaceholderText("请输入玩具描述（可选）");
    formLayout->addRow("描述:", m_descriptionEdit);
    
    mainLayout->addLayout(formLayout);
    
    // 工序选择区域
    QLabel *processLabel = new QLabel("关联工序:");
    processLabel->setStyleSheet("font-weight: bold; margin-top: 10px;");
    mainLayout->addWidget(processLabel);
    
    m_processListWidget = new QListWidget();
    m_processListWidget->setMaximumHeight(150);
    m_processListWidget->setToolTip("请选择该玩具涉及的工序，可多选");
    mainLayout->addWidget(m_processListWidget);
    
    // 已选工序显示
    m_selectedProcessesLabel = new QLabel("已选工序: 无");
    m_selectedProcessesLabel->setStyleSheet("color: #666; font-size: 12px; margin-top: 5px;");
    m_selectedProcessesLabel->setWordWrap(true);
    mainLayout->addWidget(m_selectedProcessesLabel);
    
    // 按钮
    m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    mainLayout->addWidget(m_buttonBox);
    
    connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    
    // 初始验证
    validateInput();
}

void ToyDialog::loadProcesses()
{
    m_processListWidget->clear();
    m_processMap.clear();
    
    QSqlQuery query("SELECT id, process_id, name, piece_rate FROM processes WHERE status = '启用' ORDER BY process_id");
    while (query.next()) {
        int id = query.value(0).toInt();
        QString processId = query.value(1).toString();
        QString name = query.value(2).toString();
        double pieceRate = query.value(3).toDouble();
        
        QString displayText = QString("%1 - %2 (¥%3)").arg(processId).arg(name).arg(pieceRate, 0, 'f', 2);
        QListWidgetItem *item = new QListWidgetItem(displayText);
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(Qt::Unchecked);
        item->setData(Qt::UserRole, id); // 存储工序 ID
        
        m_processListWidget->addItem(item);
        m_processMap[id] = name;
    }
}

void ToyDialog::onProcessSelectionChanged()
{
    QStringList selectedProcesses;
    for (int i = 0; i < m_processListWidget->count(); ++i) {
        QListWidgetItem *item = m_processListWidget->item(i);
        if (item->checkState() == Qt::Checked) {
            int processId = item->data(Qt::UserRole).toInt();
            selectedProcesses << m_processMap[processId];
        }
    }
    
    if (selectedProcesses.isEmpty()) {
        m_selectedProcessesLabel->setText("已选工序: 无");
    } else {
        m_selectedProcessesLabel->setText("已选工序: " + selectedProcesses.join(", "));
    }
    
    validateInput();
}

void ToyDialog::updateProcessSelection(const QList<int> &processIds)
{
    for (int i = 0; i < m_processListWidget->count(); ++i) {
        QListWidgetItem *item = m_processListWidget->item(i);
        int itemProcessId = item->data(Qt::UserRole).toInt();
        
        if (processIds.contains(itemProcessId)) {
            item->setCheckState(Qt::Checked);
        } else {
            item->setCheckState(Qt::Unchecked);
        }
    }
    onProcessSelectionChanged();
}

void ToyDialog::setToyData(const QString &toyId, const QString &name, 
                          const QString &description, const QList<int> &processIds)
{
    m_toyIdEdit->setText(toyId);
    m_nameEdit->setText(name);
    m_descriptionEdit->setText(description);
    updateProcessSelection(processIds);
}

QString ToyDialog::getToyId() const
{
    return m_toyIdEdit->text().trimmed();
}

QString ToyDialog::getName() const
{
    return m_nameEdit->text().trimmed();
}

QString ToyDialog::getDescription() const
{
    return m_descriptionEdit->text().trimmed();
}

QList<int> ToyDialog::getSelectedProcessIds() const
{
    QList<int> processIds;
    for (int i = 0; i < m_processListWidget->count(); ++i) {
        QListWidgetItem *item = m_processListWidget->item(i);
        if (item->checkState() == Qt::Checked) {
            processIds << item->data(Qt::UserRole).toInt();
        }
    }
    return processIds;
}

void ToyDialog::setEditMode(bool editMode)
{
    m_isEditMode = editMode;
    m_toyIdEdit->setReadOnly(editMode);
    
    if (editMode) {
        setWindowTitle("编辑玩具信息");
    } else {
        setWindowTitle("添加玩具");
    }
}

void ToyDialog::validateInput()
{
    bool valid = !m_toyIdEdit->text().trimmed().isEmpty() && 
                 !m_nameEdit->text().trimmed().isEmpty() &&
                 !getSelectedProcessIds().isEmpty();
    
    m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
    
    // 更新提示信息
    if (getSelectedProcessIds().isEmpty()) {
        m_selectedProcessesLabel->setStyleSheet("color: red; font-size: 12px; margin-top: 5px;");
    } else {
        m_selectedProcessesLabel->setStyleSheet("color: #666; font-size: 12px; margin-top: 5px;");
    }
}